package com.example.market.service;

import com.example.market.exception.ExceptionEnum;
import com.example.market.exception.ServiceException;
import com.example.market.pojo.User;
import com.example.market.mapper.UserMapper;
import com.example.market.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserService {
//    @Autowired
    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    public User login(User user) {
        user.setPassword(MD5.MD5Encode(user.getPassword() + "", "UTF-8"));
        User one = userMapper.selectOne(user);
        if (one == null) {
            throw new ServiceException(ExceptionEnum.GET_USR_PASSWORD_NOT_MATCH);
        }
        return one;
}
    public void register(User user) {
        User one = new User();
        one.setUsername(user.getUsername());
        if (userMapper.selectCount(one) == 1) throw new ServiceException(ExceptionEnum.User_Name_Already_Exists);
        user.setPassword(MD5.MD5Encode(user.getPassword() + "", "UTF-8"));
        try {
            userMapper.insert(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(ExceptionEnum.SAVE_USER_ERROR);
        }
    }
    public void isUserName(String username) {
        User one = new User();
        one.setUsername(username);
        // 先去看看用户名是否重复
        if (userMapper.selectCount(one) == 1) {
            // 用户名已存在
            throw new ServiceException(ExceptionEnum.User_Name_Already_Exists);
        }
    }
}
